﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using System.Text;
using KL.Store.Core.Domain;
using KL.Store.Web.Models;
using KL.Store.Data;
using KL.Store.Core;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.Xml;
using Rotativa;


namespace KL.Store.Web.Controllers
{
    [Authorize]
    public class ReportPanelController : KL.Store.Core.Web.BaseController
    {
        public ActionResult Index()
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            return View();
        }

        public ActionResult LastSales(int ItemCount)
        {
            if (!eStoreUser.IsReportManager)
            {
                return PartialView();
            }
            SalesModel Sales = new SalesModel();
            Sales.SalesList = dbReportPanel.GetDashboardSales(10);
            //Sales.SalesList = Sales.SalesList.OrderBy(o => o.FaturaNo).ToList();
            return PartialView("LastSales", Sales);
        }

        public ActionResult CriticalStocks(int? Page, int? AmbarId)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            ViewBag.Page = Page > 0 ? Page : 1;
            ViewBag.AmbarId = AmbarId != null ? AmbarId : 0;
            return View();
        }

        public ActionResult LastCriticalStocks(int StockCount, int MaximumStock, int Page, int StockPerPage, int AmbarId, string PageUrl = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return PartialView();
            }
            ViewBag.PageUrl = PageUrl;
            int PageStart = (Page * StockPerPage) - StockPerPage;
            int PageEnd = StockPerPage;
            CriticalStockModel Stocks = new CriticalStockModel();
            Stocks.StockList = dbReportPanel.GetCriticalStocks(StockCount, MaximumStock, AmbarId);
            Stocks.StockList = Stocks.StockList.OrderBy(o => o.StokMiktari).ThenByDescending(o => o.SonFaturaTarihi).ToList();
            int PageCount = ((Stocks.StockList.Count() - 1) / StockPerPage) + 1;
            Stocks.PageCount = PageCount;
            Stocks.Page = Page;
            Stocks.StockList = Stocks.StockList.Skip(PageStart).Take(PageEnd).ToList();
            Stocks.AmbarList = dbReportPanel.AmbarListesi();
            Stocks.AmbarId = AmbarId;
            return PartialView("LastCriticalStocks", Stocks);
        }

        public ActionResult ExportCriticalStocks(int AmbarId)
        {
            var nowDate = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            IList<CriticalStocks> Stocks = dbReportPanel.GetCriticalStocks(0, Parameters.CriticalStockAlertAmount, AmbarId);


            GridView gv = new GridView();
            gv.DataSource = from p in Stocks
                            select new
                            {
                                StokAdi = p.StokAdi,
                                StokNo = p.KartId,
                                Barkod = p.Barkod,
                                AmbarAdi = p.AmbarAdi,
                                Miktar = p.StokMiktari
                            };
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=KritikStoklar_" + nowDate + ".xls");
            Response.ContentType = "application/vnd.ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return View();
        }

        public ActionResult LookSales(int? IdAmbar, DateTime? BasTar, DateTime? BitTar, string DovizId = "TL")
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            SalesModel Sales = new SalesModel();
            Sales.AmbarList = dbReportPanel.AmbarListesi();
            ViewBag.IdAmbar = IdAmbar != null ? IdAmbar : 0;
            ViewBag.BasTar = BasTar != null ? BasTar : new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            ViewBag.BitTar = BitTar != null ? BitTar : new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            ViewBag.DovizId = DovizId;
            return View("LookSales", Sales);
        }

        public ActionResult LookSalesGet(int IdAmbar, DateTime BasTar, DateTime BitTar, string DovizId)
        {
            if (!eStoreUser.IsReportManager)
            {
                return PartialView();
            }
            SalesModel Sales = new SalesModel();
            Sales.AmbarList = dbReportPanel.AmbarListesi();
            Sales.SalesList = dbReportPanel.GetFilteredSales(IdAmbar, BasTar, BitTar, DovizId);
            return PartialView("LookSalesGet", Sales);
        }

        public ActionResult TotalStocks(int? Page)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            ViewBag.Page = Page > 0 ? Page : 1;
            return View();
        }

        public ActionResult TotalStocksGet(int Page, int StockPerPage, string PageUrl = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return PartialView();
            }
            TotalStockModel TotalStocks = new TotalStockModel();
            TotalStocks.TotalStockList = dbReportPanel.StockTotalList();
            TotalStocks.OrtalamaMaliyetToplam = TotalStocks.TotalStockList.Sum(o => o.OrtalamaMaliyet);
            TotalStocks.AlisFiyatiToplam = TotalStocks.TotalStockList.Sum(o => o.AlisFiyati);
            TotalStocks.SatisFiyatiToplam = TotalStocks.TotalStockList.Sum(o => o.SatisFiyati);
            TotalStocks.MiktarToplam = TotalStocks.TotalStockList.Sum(o => o.Miktar);
            TotalStocks.StokToplamMaliyet = TotalStocks.TotalStockList.Sum(o => o.AlisFiyati * o.Miktar);
            TotalStocks.ToplamStokAdedi = TotalStocks.MiktarToplam;
            TotalStocks.ToplamSatisTutarTahmini = TotalStocks.TotalStockList.Sum(o => o.SatisFiyati * o.Miktar);


            int PageStart = (Page * StockPerPage) - StockPerPage;
            int PageEnd = StockPerPage;
            TotalStocks.PageCount = ((TotalStocks.TotalStockList.Count() - 1) / StockPerPage) + 1;
            TotalStocks.Page = Page;
            ViewBag.PageUrl = PageUrl;

            TotalStocks.TotalStockList = TotalStocks.TotalStockList.Skip(PageStart).Take(PageEnd).ToList();
            return PartialView("TotalStocksGet", TotalStocks);
        }

        public ActionResult CCProcess(DateTime? StartDate, DateTime? EndDate, int Page = 1, int Sort = 1, string Filter = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            ViewBag.Page = Page > 0 ? Page : 1;
            ViewBag.Sort = Sort > 0 ? Sort : 1;
            ViewBag.Filter = Filter;
            ViewBag.StartDate = StartDate;
            ViewBag.EndDate = EndDate;
            return View();
        }

        public ActionResult CCProcessGet(DateTime? StartDate, DateTime? EndDate, int Page = 1, int RecordPerPage = 50, int Sort = 1, string Filter = "", string PageUrl = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            var DefaultDate = new DateTime();
            ViewBag.RecordPerPage = RecordPerPage > 0 ? RecordPerPage : 50;

            CCProcessModel CCProcess = new CCProcessModel { PaymentList = dbReportPanel.CCProcessList() };
            if (StartDate == null || StartDate == DefaultDate)
            {
                StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            }
            if (EndDate == null || EndDate == DefaultDate)
            {
                EndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            }


            //T veya "" Tümü; filtreleme yapma, K=Kredi Kartı, M=Mail Order
            if (Filter != "T" && Filter != "")
            {
                CCProcess.PaymentList = CCProcess.PaymentList.Where(o => o.Model == Filter).ToList();
            }
            if (StartDate != null && EndDate != null && StartDate != DefaultDate && EndDate != DefaultDate)
            {
                CCProcess.PaymentList = CCProcess.PaymentList.Where(o => o.CreateDate <= EndDate && o.CreateDate >= StartDate).ToList();
            }

            int PageStart = (Page * RecordPerPage) - RecordPerPage;
            int PageEnd = RecordPerPage;
            CCProcess.PageCount = ((CCProcess.PaymentList.Count() - 1) / RecordPerPage) + 1;
            CCProcess.Page = Page;
            CCProcess.Sort = Sort;
            CCProcess.Filter = Filter;
            CCProcess.StartDate = (DateTime)StartDate;
            CCProcess.EndDate = (DateTime)EndDate;
            ViewBag.PageUrl = PageUrl;
            //1=Tarih, 2=Tip, 3=İsim, 4=Ödeme, 5=Order No
            if (Sort == 1)
            {
                CCProcess.PaymentList = CCProcess.PaymentList.OrderByDescending(o => o.CreateDate).ToList();
            }
            else if (Sort == 2)
            {
                CCProcess.PaymentList = CCProcess.PaymentList.OrderBy(o => o.Model).ToList();
            }
            else if (Sort == 3)
            {
                CCProcess.PaymentList = CCProcess.PaymentList.OrderBy(o => o.FirstName).ThenBy(o => o.LastName).ToList();
            }
            else if (Sort == 4)
            {
                CCProcess.PaymentList = CCProcess.PaymentList.OrderByDescending(o => o.Payment).ToList();
            }
            else if (Sort == 5)
            {
                CCProcess.PaymentList = CCProcess.PaymentList.OrderBy(o => o.OrderNo).ToList();
            }

            CCProcess.PaymentList = CCProcess.PaymentList.Skip(PageStart).Take(PageEnd).ToList();

            return View(CCProcess);
        }

        public ActionResult SalesList(DateTime? StartDate, DateTime? EndDate, int Page = 1, int Sort = 1, int Order = 1, int WithCancelAndComplete = 0, int SendMailWhenChangeStatus = 1, string Durum = "", string Cari = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            ViewBag.Page = Page;
            ViewBag.Sort = Sort;
            ViewBag.Order = Order;
            ViewBag.Durum = Durum;
            ViewBag.Cari = Cari;
            ViewBag.SendMailWhenChangeStatus = SendMailWhenChangeStatus;
            ViewBag.WithCancelAndComplete = WithCancelAndComplete;
            var defaultDate = new DateTime();
            ViewBag.StartDate = (StartDate == null || StartDate == defaultDate) ? DateTime.Today.AddDays(-15) : (DateTime)StartDate;
            ViewBag.EndDate = (EndDate == null || EndDate == defaultDate) ? new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59) : (DateTime)EndDate;
            return View();
        }

        public ActionResult SalesListGet(DateTime StartDate, DateTime EndDate, int Page = 1, int RecordPerPage = 50, int Sort = 1, int Order = 1, int WithCancelAndComplete = 0, int SendMailWhenChangeStatus = 0, int Durum = 0, string Cari = "", string PageUrl = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }

            var s = new SatisSiparisModel
            {
                Page = Page,
                PageUrl = PageUrl,
                Sort = Sort,
                Order = Order,
                WithCancelAndComplete = WithCancelAndComplete,
                CariAdi = Cari,
                DurumId = Durum,
                SendMailWhenChangeStatus = SendMailWhenChangeStatus,
                StartDate = StartDate,
                EndDate = EndDate,
                SalesList = dbReportPanel.SiparisListesiSatis(WithCancelAndComplete == 1, StartDate, EndDate),
                SiparisDurumlari = dbReportPanel.SiparisDurumlari(),
                SiparisDurumGuncelle = dbReportPanel.SiparisDurumlari()
            };
            s.OdemeSekilleri.Add(new OdemeSekli { Kisa = "AK", Uzun = "Anında Kredi" });
            s.OdemeSekilleri.Add(new OdemeSekli { Kisa = "H", Uzun = "Havale/Eft" });
            s.OdemeSekilleri.Add(new OdemeSekli { Kisa = "K", Uzun = "Kredi Kartı" });
            s.OdemeSekilleri.Add(new OdemeSekli { Kisa = "M", Uzun = "Kapıda Ödeme" });
            s.OdemeSekilleri.Add(new OdemeSekli { Kisa = "N", Uzun = "Nakit" });
            s.OdemeSekilleri.Add(new OdemeSekli { Kisa = "S", Uzun = "Senetle Ödeme" });
            s.SiparisDurumGuncelle.RemoveAt(0);

            if (Durum > 0)
                s.SalesList = s.SalesList.Where(o => o.DurumId == Durum).ToList();
            if (!string.IsNullOrEmpty(Cari))
                s.SalesList = s.SalesList.Where(o => o.FaturaAdi.ToLower().Contains(Cari.ToLower())).ToList();

            switch (Sort)
            {
                case 1:
                    s.SalesList = Order == 1 ? s.SalesList.OrderByDescending(o => o.SiparisId).ToList() : s.SalesList.OrderBy(o => o.SiparisId).ToList();
                    break;
                case 2:
                    s.SalesList = Order == 1 ? s.SalesList.OrderByDescending(o => o.FaturaAdi).ToList() : s.SalesList.OrderBy(o => o.FaturaAdi).ToList();
                    break;
                case 3:
                    s.SalesList = Order == 1 ? s.SalesList.OrderByDescending(o => o.Tarih).ToList() : s.SalesList.OrderBy(o => o.Tarih).ToList();
                    break;
                case 4:
                    s.SalesList = Order == 1 ? s.SalesList.OrderByDescending(o => o.OdemeSekli).ToList() : s.SalesList.OrderBy(o => o.OdemeSekli).ToList();
                    break;
                case 5:
                    s.SalesList = Order == 1 ? s.SalesList.OrderByDescending(o => o.DurumId).ToList() : s.SalesList.OrderBy(o => o.DurumId).ToList();
                    break;
            }

            var PageStart = (Page * RecordPerPage) - RecordPerPage;
            var PageEnd = RecordPerPage;

            s.PageCount = ((s.SalesList.Count() - 1) / RecordPerPage) + 1;

            s.SalesList = s.SalesList.Skip(PageStart).Take(PageEnd).ToList();


            return View(s);
        }

        public ActionResult SalesStatusUpdate(int SiparisId, int Tip, int DurumId, int MailGonder, int CariId)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            if (SiparisId <= 0 || Tip <= 0 || DurumId <= 0)
            {
                return Content("Hata: alanlar doldurulmalıdır.");
            }
            int result = dbReportPanel.SiparisDurumGuncelle(SiparisId, Tip, DurumId);
            if (result == 1)
            {
                if (MailGonder == 1)
                {
                    var cari = dbAccount.GetById(CariId);
                    if (cari != null)
                    {
                        var MailRef = 300 + DurumId;
                        var MailContent = dbRefs.GetRef5(MailRef).Replace("{FirstName}", cari.FirstName).Replace("{LastName}", cari.LastName);
                        var Baslik = "Siparişinizin Durumu Değişmiştir";
                        switch (DurumId)
                        {
                            case 1: Baslik = "Siparişinizin Ödemesi Kontrol Edilmektedir"; break;
                            case 2: Baslik = "Siparişiniz Tedarik Sürecindedir"; break;
                            case 3: Baslik = "Siparişiniz Faturalama Aşamasındadır"; break;
                            case 4: Baslik = "Siparişiniz Kargolama Aşamasındadır"; break;
                            case 5: Baslik = "Siparişinizin Kargo Teslimi Yapılmıştır"; break;
                            case 6: Baslik = "Siparişiniz Teslim Edilmiştir"; break;
                            case 10: Baslik = "Siparişiniz İptal Edilmiştir"; break;
                            default: ; break;
                        }
                        if (!string.IsNullOrEmpty(MailContent))
                        {
                            Utils.SendMail(cari.Email, "", Parameters.OrderMailBccAddress, Baslik, MailContent, true);
                        }
                    }
                }
                return Content("Kaydedildi");
            }
            return Content("Bilgiler kaydedilirken bir hata oluştu");
        }

        public ActionResult SalesStatusNext(int SiparisId, int Tip, int MailGonder, int CariId)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            int result = dbReportPanel.SiparisDurumSonraki(SiparisId, Tip);
            if (result > 0)
            {
                if (MailGonder == 1)
                {
                    var cari = dbAccount.GetById(CariId);
                    if (cari != null)
                    {
                        var MailRef = 300 + result;
                        var MailContent = dbRefs.GetRef5(MailRef).Replace("{FirstName}", cari.FirstName).Replace("{LastName}", cari.LastName);
                        var Baslik = "Siparişinizin Durumu Değişmiştir";
                        switch (result)
                        {
                            case 1: Baslik = "Siparişinizin Ödemesi Kontrol Edilmektedir"; break;
                            case 2: Baslik = "Siparişiniz Tedarik Sürecindedir"; break;
                            case 3: Baslik = "Siparişiniz Faturalama Aşamasındadır"; break;
                            case 4: Baslik = "Siparişiniz Kargolama Aşamasındadır"; break;
                            case 5: Baslik = "Siparişinizin Kargo Teslimi Yapılmıştır"; break;
                            case 6: Baslik = "Siparişiniz Teslim Edilmiştir"; break;
                            case 10: Baslik = "Siparişiniz İptal Edilmiştir"; break;
                            default: ; break;
                        }
                        if (!string.IsNullOrEmpty(MailContent))
                        {
                            Utils.SendMail(cari.Email, "", Parameters.OrderMailBccAddress, Baslik, MailContent, true);
                        }
                    }
                }
            }
            return Content(result.ToString());
        }

        public ActionResult SalesStatusUpdateWithDate(int siparisId, int Tip, int durumId, int mailGonder, int cariId, DateTime date)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            if (siparisId <= 0 || Tip <= 0 || durumId <= 0)
            {
                return Content("Hata: alanlar doldurulmalıdır.");
            }
            int result = dbReportPanel.SiparisDurumGuncelleTeslim(siparisId, Tip, durumId, date);
            if (result == 1)
            {
                if (mailGonder == 1)
                {
                    var cari = dbAccount.GetById(cariId);
                    if (cari != null)
                    {
                        var mailRef = 300 + durumId;
                        var mailContent = dbRefs.GetRef5(mailRef).Replace("{FirstName}", cari.FirstName).Replace("{LastName}", cari.LastName);
                        var baslik = "Siparişinizin Durumu Değişmiştir";
                        switch (durumId)
                        {
                            case 1: baslik = "Siparişinizin Ödemesi Kontrol Edilmektedir"; break;
                            case 2: baslik = "Siparişiniz Tedarik Sürecindedir"; break;
                            case 3: baslik = "Siparişiniz Faturalama Aşamasındadır"; break;
                            case 4: baslik = "Siparişiniz Kargolama Aşamasındadır"; break;
                            case 5: baslik = "Siparişinizin Kargo Teslimi Yapılmıştır"; break;
                            case 6: baslik = "Siparişiniz Teslim Edilmiştir"; break;
                            case 10: baslik = "Siparişiniz İptal Edilmiştir"; break;
                            default: ; break;
                        }
                        if (!string.IsNullOrEmpty(mailContent))
                        {
                            Utils.SendMail(cari.Email, "", Parameters.OrderMailBccAddress, baslik, mailContent, true);
                        }
                    }
                }
                return Content("Kaydedildi");
            }
            return Content("Bilgiler kaydedilirken bir hata oluştu");
        }

        public ActionResult SaleDetailsGet(int SiparisId, int Tip)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            SatisSiparisDetayModel d = new SatisSiparisDetayModel
            {
                SiparisBilgi = dbReportPanel.SiparisBilgi(SiparisId, Tip),
                SatisDetay = dbReportPanel.SiparisDetay(SiparisId, Tip),
                SiparisDurumlari = dbReportPanel.SiparisDurumlari(),
                SiparisAdresler = dbReportPanel.SiparisAdresleri(SiparisId, Tip),
                SiparisBilgiFatura = dbReportPanel.SiparisBilgiFatura(SiparisId, Tip)
            };
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "AK", Uzun = "Anında Kredi" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "H", Uzun = "Havale/Eft" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "K", Uzun = "Kredi Kartı" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "M", Uzun = "Kapıda Ödeme" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "N", Uzun = "Nakit" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "S", Uzun = "Senetle Ödeme" });
            return View(d);
        }

        public ActionResult SaleDetailsGetPdf(int SiparisId, int Tip)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            SatisSiparisDetayModel d = new SatisSiparisDetayModel
            {
                SiparisBilgi = dbReportPanel.SiparisBilgi(SiparisId, Tip),
                SatisDetay = dbReportPanel.SiparisDetay(SiparisId, Tip),
                SiparisDurumlari = dbReportPanel.SiparisDurumlari(),
                SiparisAdresler = dbReportPanel.SiparisAdresleri(SiparisId, Tip),
                SiparisBilgiFatura = dbReportPanel.SiparisBilgiFatura(SiparisId, Tip)
            };
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "AK", Uzun = "Anında Kredi" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "H", Uzun = "Havale/Eft" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "K", Uzun = "Kredi Kartı" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "M", Uzun = "Kapıda Ödeme" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "N", Uzun = "Nakit" });
            d.OdemeSekilleri.Add(new OdemeSekli { Kisa = "S", Uzun = "Senetle Ödeme" });
            return new ViewAsPdf("SaleDetailsGetPdf", d);
        }

        public ActionResult SenetCiktisi(int UserId, int SiparisId, int Tip)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            SenetCiktisiModel s = new SenetCiktisiModel
            {
                SiparisBilgi = dbReportPanel.SiparisBilgi(SiparisId, Tip),
                SatisDetay = dbReportPanel.SiparisDetay(SiparisId, Tip),
                VC = dbVoucher.GetByOrderId(UserId, SiparisId)
            };
            var InstallmentCount = s.VC.InstallmentNo;
            var PaymentAmount = s.VC.PaymentAmount;
            var VoucherDate = s.VC.CreateDate.Day.ToString() + "/" + s.VC.CreateDate.Month.ToString() + "/" + s.VC.CreateDate.Year.ToString();
            s.UI = dbAccount.GetOrderUserInfo((int)s.VC.VoucherId);
            string MessageBody = dbRefs.GetRef5(125);
            string table = "";

            string MemberInfo1 = "";
            table = "<tbody>";
            table += "<tr>";
            table += "<td style=\"text-align: center; border: 1px solid #000000;\">Kod</td>";
            table += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Malın Cinsi</td>";
            table += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Adedi</td>";
            table += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Birim Fiyatı</td>";
            table += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Tutarı</td>";
            table += "</tr>";
            foreach (var rows in s.SatisDetay)
            {
                string StockPrice = "";
                StockPrice = (rows.GenelToplam).ToString("###,###,##0.00") + " " + rows.ParaCins;

                table += "<tr>";
                table += "<td style=\"text-align: center; border-right: 1px solid #000000; border-left: 1px solid #000000;\">" + rows.StokId + "</td> ";
                table += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + rows.Aciklama + (!string.IsNullOrEmpty(rows.Model) ? " - " + rows.Model : "") + "</td>";
                table += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + rows.StokMiktar.ToString("###,###.###") + " Adet</td>";
                table += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + (rows.GenelToplam / rows.StokMiktar).ToString("###,###,##0.00") + " " + rows.ParaCins + "</td>";
                table += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + StockPrice + "</td>";
                table += " </tr>";
            }
            table += "<tr>";
            table += "<td style=\"text-align:right; border-top: 1px solid #000000; border-right: 1px solid #000000; border-left: 1px solid #000000;\" colspan=\"4\"><b>Toplam&nbsp;</b></td>";
            table += "<td style=\"text-align: center; border-top: 1px solid #000000; border-right: 1px solid #000000;\"><b>" + (s.SiparisBilgi.GenelToplam).ToString("###,###,##0.00") + " TL</b></td>";
            table += "</tr>";
            table += "<tr>";
            table += "<td style=\"text-align:right; border-top: 1px solid #000000; border-right: 1px solid #000000; border-left: 1px solid #000000;\" colspan=\"4\"><b>Taksit Sayısı&nbsp;</b></td>";
            table += "<td style=\"text-align: center; border-top: 1px solid #000000; border-right: 1px solid #000000;\"><b>" + (s.VC.InstallmentNo).ToString("###,###,##0") + "</b></td>";
            table += "</tr>";
            table += "</tbody>";


            if (s.UI.Kimlik != null)
            {
                #region MemberInfo Table
                MemberInfo1 += "<tr>";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 15%;\">Adı Soyadı</td>";
                string DogumTarihiStr = s.UI.Kimlik.DogumTarihi.Day.ToString() + "/" + s.UI.Kimlik.DogumTarihi.Month.ToString() + "/" + s.UI.Kimlik.DogumTarihi.Year.ToString();
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 22%;\">" + s.UI.Kimlik.FirstName + " " + s.UI.Kimlik.LastName + "<br />T.C. :" + s.UI.Kimlik.N_TCKimlikNo + " - " + DogumTarihiStr + "</td>";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%; text-align: center;\" rowspan=\"3\">İş<br />Adresi</td>";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; text-align: center;\" rowspan=\"3\">'Görevi: " + s.UI.Kimlik.IsGorev + "' - " + s.UI.Kimlik.IsYeriAdi + " - " + s.UI.Kimlik.IsAdres + "</td>";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%;\">Ev Tel</td>";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; border-right: 1px solid #000000;\">" + s.UI.Kimlik.EvTel + "</td>";
                MemberInfo1 += "</tr>";
                MemberInfo1 += "<tr>";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev Adresi</td>";
                MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + s.UI.Kimlik.EvAdres + "</td>";
                MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">Gsm</td>";
                MemberInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + s.UI.Kimlik.CepTel + "</td>";
                MemberInfo1 += "</tr>";
                MemberInfo1 += "<tr>";
                var evkira = (s.UI.Kimlik.EvKira) ? "Kendi Evi" : "Kiracı";
                MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev</td>";
                MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + evkira + "</td>";
                MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">İş Tel</td>";
                MemberInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + s.UI.Kimlik.IsTel + "</td>";
                MemberInfo1 += "</tr>";
                #endregion
            }
            #region Guarantors Table
            string GuarantorInfo1 = "";
            foreach (Guarantor Kefil in s.UI.Kefiller)
            {
                GuarantorInfo1 += "<tr>";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 15%;\">Müşterek Müteselsil Kefilin Adı Soyadı</td>";
                string KflDogumTarihiStr = Kefil.DogumTarihi.Day.ToString() + "/" + Kefil.DogumTarihi.Month.ToString() + "/" + Kefil.DogumTarihi.Year.ToString();
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 22%;\">" + Kefil.FirstName + " " + Kefil.LastName + "<br />T.C. :" + Kefil.N_TCKimlikNo + " - " + KflDogumTarihiStr + "</td>";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%; text-align: center;\" rowspan=\"3\">İş<br />Adresi</td>";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; text-align: center;\" rowspan=\"3\">'Görevi: " + Kefil.IsGorev + "' - " + Kefil.IsYeriAdi + " - " + Kefil.IsAdres + "</td>";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%;\">Ev Tel</td>";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; border-right: 1px solid #000000;\">" + Kefil.EvTel + "</td>";
                GuarantorInfo1 += "</tr>";
                GuarantorInfo1 += "<tr>";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev Adresi</td>";
                GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + Kefil.EvAdres + "</td>";
                GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">Gsm</td>";
                GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + Kefil.CepTel + "</td>";
                GuarantorInfo1 += "</tr>";
                GuarantorInfo1 += "<tr>";
                var Kflevkira = (Kefil.EvKira) ? "Kendi Evi" : "Kiracı";
                GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev</td>";
                GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + Kflevkira + "</td>";
                GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">İş Tel</td>";
                GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + Kefil.IsTel + "</td>";
                GuarantorInfo1 += "</tr>";
            }
            #endregion

            var Guarantor1FullName = "";
            var Guarantor2FullName = "";
            if (s.UI.Kefiller.Any())
            {
                Guarantor1FullName = s.UI.Kefiller.FirstOrDefault().FirstName + " " + s.UI.Kefiller.FirstOrDefault().LastName;
            }
            if (s.UI.Kefiller.Count() > 1)
            {
                Guarantor2FullName = s.UI.Kefiller.Skip(1).FirstOrDefault().FirstName + " " + s.UI.Kefiller.FirstOrDefault().LastName;
            }

            #region VoucherSection
            var MemberInfo2 = "";
            var GuarantorInfo2 = "";

            if (s.UI.Kimlik != null)
            {
                MemberInfo2 = "<td>İsim:<br />Adres:</td>";
                MemberInfo2 += "<td>" + s.UI.Kimlik.FirstName + " " + s.UI.Kimlik.LastName + "<br />";
                MemberInfo2 += s.UI.Kimlik.EvAdres + " " + s.UI.Kimlik.N_Mahalle + " " + s.UI.Kimlik.N_Ilce + "/" + s.UI.Kimlik.N_KutukIl + "</td>";
            }
            int AvlCounter = 1;
            foreach (Guarantor Kefil in s.UI.Kefiller)
            {
                GuarantorInfo2 += "<tr>";
                GuarantorInfo2 += "<td>" + AvlCounter.ToString() + ". Avalist:<br />";
                GuarantorInfo2 += "Adres:</td>";
                GuarantorInfo2 += "<td>" + Kefil.FirstName + " " + Kefil.LastName + "<br />";
                GuarantorInfo2 += "" + Kefil.EvAdres + " " + Kefil.N_Mahalle + " " + Kefil.N_Ilce + "/" + Kefil.N_KutukIl + "</td>";
                GuarantorInfo2 += "</tr>";
                AvlCounter++;
            }
            #endregion


            MessageBody = MessageBody.Replace("{FirstName}", (s.UI.Kimlik == null ? "" : s.UI.Kimlik.FirstName)).Replace("{LastName}", (s.UI.Kimlik == null ? "" : s.UI.Kimlik.LastName)).Replace("{ProductsTable}", table).Replace("{InstallmentCount}", InstallmentCount.ToString());
            MessageBody = MessageBody.Replace("{PaymentAmount}", PaymentAmount.ToString("###,###,##0.00")).Replace("{VoucherNumber}", s.VC.VoucherId.ToString()).Replace("{VoucherDate}", VoucherDate).Replace("{MemberInfo1}", MemberInfo1);
            MessageBody = MessageBody.Replace("{GuarantorInfo1}", GuarantorInfo1).Replace("{Guarantor1FullName}", Guarantor1FullName).Replace("{Guarantor2FullName}", Guarantor2FullName).Replace("{MemberInfo2}", MemberInfo2).Replace("{GuarantorInfo2}", GuarantorInfo2);

            s.TemplateStr = MessageBody;
            return new ViewAsPdf("SenetCiktisi", s);
        }

        public ActionResult Kategori()
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            return View();
        }

        public ActionResult KategoriMenusu(int selectedCategory = 0)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            StokGrupMenuModel Model = new StokGrupMenuModel();
            Model.MenuList = dbReportPanel.CategoryMenuListGet();
            Model.MenuString = dbReportPanel.CategoryMenuListHtml(Model.MenuList, selectedCategory);

            return View(Model);
        }

        public ActionResult KategoriDuzenle(int CategoryId, int ParentCategoryId = 0, string Message = "")
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            StokGrupDuzenleModel Model = new StokGrupDuzenleModel();
            if (ParentCategoryId > 0)
            {
                CategoryEdit ct = new CategoryEdit();
                ct = dbReportPanel.GetCategoryEdit(ParentCategoryId);
                Model.Category.ParentCategoryId = ct.CategoryId;
                Model.Category.ParentCategoryName = ct.CategoryName;
                Model.Category.CategoryType = ct.CategoryType;
                Model.Category.eStoreImageType = ct.eStoreImageType;
                Model.Category.ShowOnEStore = ct.ShowOnEStore;
                Model.Category.Transport = ct.Transport;
                Model.AddNew = true;
            }
            else
            {
                Model.Category = dbReportPanel.GetCategoryEdit(CategoryId);
                Model.ExtraFields = dbReportPanel.GetCategoryExtraFields(CategoryId);
            }
            Model.Message = Message;
            Model.Password = dbRefs.GetRef1Old(1911);
            return View(Model);
        }

        [HttpPost]
        public ActionResult KategoriDuzenle2(CategoryEdit Category, int IdForPost)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            int result = 0;
            if (Category.CategoryId == 0)
            {
                if (string.IsNullOrEmpty(Category.CategoryName) || string.IsNullOrEmpty(Category.ParentCategoryId.ToString()) || Category.ParentCategoryId <= 0 || string.IsNullOrEmpty(Category.CategoryType))
                {
                    return JavaScript("hataMesaji('Lütfen tüm gerekli alanları doldurun');");
                }
                else
                {
                    result = dbReportPanel.AddNewCategory(Category);
                    return JavaScript(result > 0 ? "kategoriEklendi(" + result + ");" : "hataMesaji('Kategori eklenirken bir hata oluştu');");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(Category.CategoryName) || string.IsNullOrEmpty(Category.ParentCategoryId.ToString()) || Category.ParentCategoryId <= 0 || string.IsNullOrEmpty(Category.CategoryType) || string.IsNullOrEmpty(Category.CategoryId.ToString()) || Category.CategoryId <= 0 || string.IsNullOrEmpty(Category.GroupCode) || string.IsNullOrEmpty(Category.ProductGroupCode))
                {
                    return JavaScript("hataMesaji('Lütfen tüm gerekli alanları doldurun');");
                }
                else
                {
                    result = dbReportPanel.SaveCategoryEdit(Category);
                    return JavaScript(result == 1 ? "kategoriGuncellendi(" + Category.CategoryId + ");" : "hataMesaji('Kategori bilgileri güncellenirken bir hata oluştu');");
                }
            }
        }

        [HttpPost]
        public ActionResult KategoriSil(int CategoryId, int ParentCategoryId)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            if (ParentCategoryId <= 1)
            {
                return JavaScript("hataMesaji('Ana kategoriler silinemez.');");
            }
            else
            {
                int result = dbReportPanel.RemoveCategory(CategoryId);
                if (result == 1)
                {
                    return JavaScript("kategoriSilindi(" + ParentCategoryId.ToString() + ");");
                }
                else if (result == 0)
                {
                    return JavaScript("hataMesaji('Silme işlemi sırasında bir hata oluştu.');");
                }
                else if (result == -1)
                {
                    return JavaScript("hataMesaji('Alt kategorisi olan kategoriler silinemez.');");
                }
                else if (result == -2)
                {
                    return JavaScript("hataMesaji('Ana kategoriler silinemez.');");
                }
                else
                {
                    return JavaScript("hataMesaji('Silme işlemi sırasında bir hata oluştu.');");
                }
            }
        }

        [HttpPost]
        public ActionResult KategoriExtraAlanGuncelle(string Field, string Value, int CategoryId, int SatirNo, string Original)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            var result = dbReportPanel.UpdateExtraField(Field, Value, CategoryId, SatirNo, Original);
            return result == 1 ? Content("success") : Content("error");
        }

        [HttpPost]
        public ActionResult KategoriExtraAlanEkle(int CategoryId, int SatirNo, string Aciklama, string Bilgi, short EstoreGoster)
        {
            if (!eStoreUser.IsReportManager)
            {
                return Redirect(Parameters.WebSiteUrl);
            }
            var result = dbReportPanel.AddExtraField(CategoryId, SatirNo, Aciklama, Bilgi, EstoreGoster);
            return result == 1 ? JavaScript("ekstraAlanEklendi();") : (result == -1 ? JavaScript("hataMesaji('Aynı Satır No ile başka kayıtlar mevcut.');") : JavaScript("hataMesaji('Ekleme işlemi sırasında bir hata oluştu.');"));
        }

        public ActionResult Stok()
        {
            return View();
        }

        public ActionResult StokArama(string Search)
        {
            if (!string.IsNullOrEmpty(Search)) Search = HttpUtility.UrlDecode(Search);
            if (Search.Length < 2) return Content("<div class=\"col-xs-12 col-sm-12 col-md-9 col-lg-10 right\"><div class=\"bg-info bs-bgb\" style=\"margin-bottom: 15px; color: #000000;\"><span class=\"glyphicon glyphicon-info-sign\"></span>&nbsp;Arama kriteri giriniz.</div></div>");
            ProductsModel productsModel = new ProductsModel();
            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.IsSeoManager = eStoreUser.IsSeoManager;
            var id = 0;
            var brand = 0;
            if (string.IsNullOrEmpty(Search)) Search = "";

            productsModel.RelatedProducts = dbProduct.GetListFull((int)id, 0, (int)brand, eStoreUser.AccountId, Search).OrderBy(o => o.ProductName).ToArray<Product>();

            productsModel.RelatedItemCount = productsModel.RelatedProducts.Count();


            productsModel.BreadCrumb = "";


            return View(productsModel);
        }

        public ActionResult StokFiltre(int SelectedCategory = 0)
        {
            GroupMenuModel Model = new GroupMenuModel();
            Model.GroupList = dbReportPanel.CategoryMenuListGet().OrderBy(g => g.CategoryType).ThenBy(g => g.CategoryName).ToList();
            Model.GroupListA = Model.GroupList.Where(g => g.CategoryType == "A").ToList();
            Model.GroupListM = Model.GroupList.Where(g => g.CategoryType == "M").ToList();
            Model.GroupListS = Model.GroupList.Where(g => g.CategoryType == "S").ToList();
            Model.SelectedGroup = SelectedCategory;
            return View(Model);
        }

        public ActionResult StokFiltreGet(int SelectedCategory = 0, int SelectedBrand = 0, int SelectedPage = 0, int order = 1, int sort = 1, string FreeCargo = "T", string FastCargo = "T", string NewProduct = "T", string OpportunityProduct = "T", string CampaignProduct = "T", string ShowAsCampaignProduct = "T", string GiftString = "T", string SpecialText = "T", string CheckStock = "T")
        {
            ProductsModel productsModel = new ProductsModel();
            productsModel.IsManager = eStoreUser.IsManager;
            productsModel.IsSeoManager = eStoreUser.IsSeoManager;

            #region Variables to VB

            //ViewBag.ProductName=ProductName;
            ViewBag.SelectedCategory = SelectedCategory;
            ViewBag.SelectedBrand = SelectedBrand;
            ViewBag.SelectedPage = SelectedPage;
            ViewBag.FreeCargo = FreeCargo;
            ViewBag.FastCargo = FastCargo;
            ViewBag.NewProduct = NewProduct;
            ViewBag.OpportunityProduct = OpportunityProduct;
            ViewBag.CampaignProduct = CampaignProduct;
            ViewBag.ShowAsCampaignProduct = ShowAsCampaignProduct;
            ViewBag.GiftString = GiftString;
            ViewBag.SpecialText = SpecialText;
            ViewBag.CheckStock = CheckStock;
            ViewBag.Sort = sort;
            ViewBag.Order = order;

            #endregion

            productsModel.RelatedProducts = dbProduct.GetListFullWithFilter(SelectedCategory, SelectedBrand, SelectedPage, 0, FreeCargo, FastCargo, NewProduct, OpportunityProduct, CampaignProduct, ShowAsCampaignProduct, GiftString, SpecialText, CheckStock).OrderBy(o => o.ProductName).ToArray<Product>();

            if (order == 1)
            {
                //Order By ProductName
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.ProductName).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.ProductName).ToList();
            }
            else if (order == 2)
            {
                //Order By FreeCargo
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.FreeCargo).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.FreeCargo).ToList();
            }
            else if (order == 3)
            {
                //Order By FastCargo
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.FastCargo).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.FastCargo).ToList();
            }
            else if (order == 4)
            {
                //Order By NewProduct
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.NewProduct).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.NewProduct).ToList();
            }
            else if (order == 5)
            {
                //Order By OpportunityProduct
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.OpportunityProduct).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.OpportunityProduct).ToList();
            }
            else if (order == 6)
            {
                //Order By CampaignProduct
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.CampaignProduct).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.CampaignProduct).ToList();
            }
            else if (order == 7)
            {
                //Order By ShowAsCampaignProduct
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.ShowAsCampaignProduct).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.ShowAsCampaignProduct).ToList();
            }
            else if (order == 8)
            {
                //Order By CheckStock
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => o.CheckStock).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => o.CheckStock).ToList();
            }
            else if (order == 9)
            {
                //Order By GiftString
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => string.IsNullOrEmpty(o.GiftString)).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => string.IsNullOrEmpty(o.GiftString)).ToList();
            }
            else if (order == 10)
            {
                //Order By SpecialText
                if (sort == 1)
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderBy(o => string.IsNullOrEmpty(o.SpecialText)).ToList();
                else
                    productsModel.RelatedProducts = productsModel.RelatedProducts.OrderByDescending(o => string.IsNullOrEmpty(o.SpecialText)).ToList();
            }

            productsModel.RelatedItemCount = productsModel.RelatedProducts.Count();
            productsModel.BreadCrumb = "";

            return View(productsModel);
        }

        public ActionResult StokFiltreSet(int ProductId, string Field = "", string ValueTF = "", string ValueEH = "", string ValueText = "")
        {
            string result = "";
            int set = 0;
            if (Field == "")
            {
                result = "fail";
            }
            if (Field == "STOKTUT")
            {
                if (string.IsNullOrEmpty(ValueEH))
                {
                    result = "fail";
                }
                else
                {
                    set = dbReportPanel.UpdateProductCheckStock(ProductId, ValueEH);
                    result = set == 1 ? "success" : "fail";
                }
            }
            else if (Field == "GIFTSTRING" || Field == "OZELMETIN")
            {
                set = dbReportPanel.UpdateProductTextField(ProductId, Field, ValueText);
                result = set == 1 ? "success" : "fail";
            }
            else if (Field == "UCRETSIZKARGO" || Field == "HIZLIKARGO" || Field == "YENIURUN" || Field == "FIRSATURUN" || Field == "KAMPANYALIURUN" || Field == "KAMPANYALIGOSTER")
            {
                if (string.IsNullOrEmpty(ValueTF))
                {
                    result = "fail";
                }
                else
                {
                    set = dbReportPanel.UpdateProductBitField(ProductId, Field, ValueTF);
                    result = set == 1 ? "success" : "fail";
                }
            }
            else
            {
                result = "fail";
            }
            return Content(result);
        }

        public ActionResult StokCokluIslem()
        {
            return View();
        }

        public ActionResult GetProductForEdit(int ProductId)
        {
            var result = "fail";
            if (ProductId > 0)
            {
                Product p = dbProduct.Get2(ProductId);
                if (p != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<tr id=\"Product" + p.ProductId + "\" data-id=\"" + p.ProductId + "\">");
                    sb.Append("<td>" + p.ProductName + " (" + p.ProductId + ")</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"FreeCargoField\">" + (p.FreeCargo ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"FastCargoField\">" + (p.FastCargo ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"NewProductField\">" + (p.NewProduct ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"OpportunityProductField\">" + (p.OpportunityProduct ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"CampaignProductField\">" + (p.CampaignProduct ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"ShowAsCampaignProductField\">" + (p.ShowAsCampaignProduct ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"CheckStockField\">" + (p.CheckStock ? "<b>Evet</b>" : "Hayır") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"GiftStringField\">" + (!string.IsNullOrEmpty(p.GiftString) ? "<b>Dolu</b>" : "Boş") + "</td>");
                    sb.Append("<td style=\"text-align: center;\" class=\"SpecialTextField\">" + (!string.IsNullOrEmpty(p.SpecialText) ? "<b>Dolu</b>" : "Boş") + "</td>");
                    sb.Append("<td style=\"text-align: center;\"><input type=\"checkbox\" name=\"product[]\" class=\"SelectedProduct\" id=\"ProductSelect" + p.ProductId + "\" data-id=\"" + p.ProductId + "\" /></td>");
                    sb.Append("</tr>");
                    result = sb.ToString();
                }
                else
                {
                    result = "fail";
                }
            }
            return Content(result);
        }

        public ActionResult StokExport(int SelectedCategory = 0)
        {
            GroupMenuModel Model = new GroupMenuModel();
            Model.GroupList = dbReportPanel.CategoryMenuListGet().OrderBy(g => g.CategoryType).ThenBy(g => g.CategoryName).ToList();
            Model.GroupListA = Model.GroupList.Where(g => g.CategoryType == "A").ToList();
            Model.GroupListM = Model.GroupList.Where(g => g.CategoryType == "M").ToList();
            Model.GroupListS = Model.GroupList.Where(g => g.CategoryType == "S").ToList();
            Model.SelectedGroup = SelectedCategory;
            return View(Model);
        }

        public ActionResult StokExportXls(int SelectedCategory, short AddedType, short IsActive)
        {
            var nowDate = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            var groupName = "TumStoklar";
            if (SelectedCategory > 0)
            {
                Category c = dbCategory.Get(SelectedCategory);
                if (c != null)
                {
                    groupName = Utils.SefText(c.CategoryName);
                }
            }
            IList<Product> Products = dbProduct.GetListForExport(SelectedCategory, AddedType, IsActive);


            GridView gv = new GridView();
            gv.DataSource = from p in Products
                            select new
                            {
                                StokNo = p.ProductId,
                                StokAdi = p.ProductName,
                                Aciklama = p.ProductName2,
                                Model = p.Model,
                                SatisFiyati = p.Price,
                                MinSatisFiyati = p.MinimumPrice,
                                AlisFiyati = p.BuyingPrice,
                                TedarikciFiyati = p.SupplierPrice,
                                BayiSatisFiyati = p.DealerSellingPrice,
                                KargoEkUcret = p.AddtCargoPrice,
                                HizliKargo = Convert.ToInt16(p.FastCargo),
                                YeniUrun = Convert.ToInt16(p.NewProduct),
                                UcretsizKargo = Convert.ToInt16(p.FreeCargo),
                                FirsatUrunu = Convert.ToInt16(p.OpportunityProduct),
                                XmlGuncelleme = p.XmlUpdate,
                                KdvOrani = p.TaxRate,
                                IndirimOrani = p.DiscountPercent,
                                IndirimTutari = p.DiscountTotal,
                                IndirimGosterimi = p.DiscountDisplayTotal,
                                UstUrunId = p.UstUrunId,
                                VariantDeger1 = p.Variant1,
                                VariantDeger2 = p.Variant2,
                                VariantDeger3 = p.Variant3,
                                XmlId = p.XmlId
                            };
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("Content-Disposition", "attachment; filename=StokExport_" + groupName + "_" + nowDate + ".xls");
            Response.ContentType = "application/vnd.ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.GridLines = GridLines.Both;
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return View();
        }

        public ActionResult Banner()
        {
            BannerMenuModel Model = new BannerMenuModel();
            Model.Password = dbRefs.GetRef1Old(1911);
            return View(Model);
        }

        public ActionResult BannerListMenu(int BannerId = 0)
        {
            BannerMenuModel Model = new BannerMenuModel();
            Model.BannerList = dbBanner.GetAll();
            Model.SelectedBanner = BannerId;
            return View(Model);
        }

        public ActionResult BannerGet(int BannerId)
        {
            BannerDuzenleModel Model = new BannerDuzenleModel();
            Model.Banner = BannerId > 0 ? dbBanner.Get(BannerId) : new Banner();
            if (BannerId == 0)
            {
                Model.Banner.IsActive = true;
                Model.Banner.PublishDate = DateTime.Now;
                Model.Banner.EndDate = DateTime.Now;
            }
            Model.Password = dbRefs.GetRef1Old(1911);
            return View(Model);
        }

        public ActionResult BannerSet(Banner banner, short IsActive)
        {
            if (string.IsNullOrEmpty(banner.Name))
            {
                return JavaScript("hataMesaji('Banner ismi girmediniz.');");
            }
            banner.Aciklama = string.IsNullOrEmpty(banner.Aciklama) ? "" : banner.Aciklama;
            banner.Html = string.IsNullOrEmpty(banner.Html) ? "" : banner.Html;
            banner.ListOrder = string.IsNullOrEmpty(banner.ListOrder.ToString()) ? (short)100 : banner.ListOrder;
            banner.Pozisyon = string.IsNullOrEmpty(banner.Pozisyon) ? "" : banner.Pozisyon;
            banner.Url = string.IsNullOrEmpty(banner.Url) ? "" : banner.Url;
            banner.IsActive = IsActive == 1 ? true : false;
            int result = dbBanner.Set(banner);
            var successJs = banner.BannerID > 0 ? "bannerGuncellendi" : "bannerEklendi";
            var successId = banner.BannerID > 0 ? banner.BannerID : result;
            return JavaScript(result >= 1 ? successJs + "(" + successId + ");" : "hataMesaji('Banner bilgileri güncellenirken bir hata oluştu');");
        }

        public ActionResult BannerDelete(int BannerId)
        {
            int result = dbBanner.Delete(BannerId);
            return Content(result == 1 ? "success" : "fail");
        }

    }
}
